const CopyWebpackPlugin = require("copy-webpack-plugin"); //文件复制插件
const path = require("path");
const webpack = require("webpack");
const ExtensionReloader = require("webpack-ext-reloader"); //浏览器扩展插件，修改后重新加载manifest文件
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); //压缩css
// const HtmlWebpackPlugin = require('html-webpack-plugin'); //压缩html

const isDev = process.env.NODE_ENV === "development";

const copyFiles = [
  {
    from: path.resolve("src/manifest.json"),
    to: path.resolve("dist"),
  },
  {
    from: path.resolve("src/assets"),
    to: path.resolve("dist/assets"),
  },
];

const hotReload = isDev
  ? [
      new ExtensionReloader({
        reloadPage: true,
        manifest: path.resolve(__dirname, "src/manifest.json"),
      }),
    ]
  : [];

module.exports = {
  productionSourceMap: false,
  pages: {
    popup: {
      entry: `src/popup/index.js`,
      template: `src/pages/popup.html`,
      filename: `html/popup.html`,
    },
    options: {
      entry: `src/options/index.js`,
      template: `src/pages/options.html`,
      filename: `html/options.html`,
    },
    tab: {
      entry: `src/tab/index.js`,
      template: `src/pages/tab.html`,
      filename: `html/tab.html`,
    },
  },
  outputDir: "dist", // 设置构建的输出目录
  assetsDir: "assets", // 静态资源目录，如 css、img 等
  configureWebpack: {
    mode: isDev ? "development" : "production",
    devtool: isDev ? "source-map" : false,
    entry: {
      content: "./src/content/index.js",
      background: "./src/background/index.js",
    },
    output: {
      filename: "js/[name].js",
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
        vue$: "vue/dist/vue.esm-bundler.js", // 指定 Vue 的入口文件
      },
      extensions: [".ts", ".js", ".vue", ".json"], // 添加 .ts 扩展
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          use: "ts-loader",
          exclude: /node_modules/,
        },
      ],
    },
    plugins: [
      new CopyWebpackPlugin({
        patterns: copyFiles,
      }),
      new webpack.DefinePlugin({
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: "false", // 禁用 SSR 水合匹配的详细信息
      }),
      ...hotReload,
    ],
    optimization: {
      minimizer: [
        new CssMinimizerPlugin(), // CSS 压缩
      ],
    },
  },
  css: {
    extract: {
      filename: "css/[name].css", // 将 CSS 文件放到 dist/css 目录
    },
  },
  chainWebpack: (config) => {
    config.optimization.delete("splitChunks");
  },
};
